package com.factory.iamp.controller;

import com.factory.iamp.pojo.Upload;
import com.factory.iamp.pojo.UploadList;
import com.factory.iamp.pojo.User;
import com.factory.iamp.service.UploadService;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.token.LoginToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/upload")
@Validated
public class UploadController {
    @Resource
    private UploadService uploadService;

    @GetMapping("/list/{limit}/{page}")
    @LoginToken
    public PageHelper getAllFile(@PathVariable("limit") int limit, @PathVariable("page") int page) {
        PageHelper result = new PageHelper(uploadService.Count(), page, limit);
        result.setData(uploadService.ListPaged(result));
        return result;
    }

    @GetMapping("/table/{tid}")
    @LoginToken
    public List<UploadList> getTableFile(@PathVariable("tid") int tid) {
        return uploadService.getTableFile(tid);
    }

    @GetMapping("/content/{oid}")
    @LoginToken
    public List<UploadList> getContentFile(@PathVariable("oid") int oid) {
        return uploadService.getContentFile(oid);
    }

    @GetMapping("/my/{limit}/{page}")
    @LoginToken
    public PageHelper getMyFile(
            @RequestAttribute("iampUser") User user,
            @PathVariable("limit") int limit,
            @PathVariable("page") int page
    ) {
        PageHelper result = new PageHelper(uploadService.MyCount(user.getUid()), page, limit);
        result.setData(uploadService.MyListPaged(result, user.getUid()));
        return result;
    }

    @PostMapping("/single/{tid}")
    @LoginToken
    public Upload uploadSingle(
            @RequestAttribute("iampUser") User user,
            @RequestParam("file") MultipartFile file,
            @PathVariable("tid") int tid
    ) throws Throwable {
        return uploadService.addFileSingle(user, file, tid);
    }

    @DeleteMapping("/my/{fid}")
    @LoginToken
    public void deleteMy(@RequestAttribute("iampUser") User user, @PathVariable("fid") int fid) {
        uploadService.deleteMyFile(user, fid);
    }
}
